import React, { Component } from 'react';
import { connect } from 'dva';
import { each, find, cloneDeep, set } from 'lodash';
import { history } from 'umi';
import { produce } from 'immer';

// const users = ({ dispatch, users }) => {
//   const setUserName = () => {
//     dispatch({
//       type: 'users/setName',
//       payload: 'B',
//     });
//   };

//   const fetchUserName = () => {
//       dispatch({
//         type: 'users/fetchUserName',
//       });
//     };

//   return (
//     <>
//       <div>姓名：{users}</div>
//       <button onClick={setUserName}>点我修改</button>
//       <button onClick={fetchUserName}>接口修改</button>
//     </>
//   );
// };

// const mapStateToProps = (state) => {
//   console.log(state);
//   return {
//     users: state.users.name,
//   };
// };
// export default connect(mapStateToProps)(users);

@connect(({ users }: any) => ({
  users: users.name,
  lis: users.lis,
}))
class Users extends Component {
  fun1 = function () {};
  fun2 = () => {};
  //定义状态
  state = { count: 0 };
  // 定义修改数据的方法
  setCount = () => {
    this.setState({
      count: this.state.count + 1,
    });
  };
  click = () => {
    history.push(`/two/${this.state.count}`);
  };

  render() {
    const { dispatch, users, lis }: any = this.props;
    const setUserName = () => {
      dispatch({
        type: 'users/setName',
        payload: 'hali',
      });
    };
    const fetchUserName = () => {
      dispatch({
        type: 'users/fetchUserName',
      });
    };

    const obj_1 = {
      a: '1',
    };
    //赋值引用数据类型，改变会影响原来的
    console.log('obj_1', obj_1);

    const obj_2 = obj_1;
    obj_2.a = '2';
    console.log('obj_1', obj_1);
    console.log('obj_2', obj_2);

    // immer 解决
    const state = {
      a: '1',
    };
    //produce包裹数据并深拷贝数据，并且可以处理，这个函数的的值是处理好的数据
    function getobj1() {
      return produce(state, (draftState: any) => {
        set(draftState, 'b', '2');
      });
    }
    const getobj2 = () => {
      const nextState = produce(state, (draftState: any) => {
        set(draftState, 'c', '3');
      });
      return { ...nextState };
    };
    console.log('getobj1()', getobj1());
    console.log('state', state);
    console.log('getobj2()', getobj2());
    console.log('state', state);

    return (
      <>
        <div>姓名： {users}</div>
        <button onClick={setUserName}>点我修改姓名</button>
        <button onClick={fetchUserName}>接口修改</button>
        <span>{lis}</span>
        <button onClick={this.click}>跳转</button>
      </>
    );
  }
}

export default Users;
